package com.axter.app.test.testpics;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhaobo on 2016/12/2.
 */

public class MenuListView extends ListView implements AdapterView.OnItemClickListener {
    private SparseArray<Object> data = new SparseArray<>();
    private ArrayAdapter<String> adapter;
    private List<String> list = new ArrayList<>();

    public MenuListView(Context context) {
        super(context);
        init();
    }

    public MenuListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MenuListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MenuListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init() {
        setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object menu = data.get(position);
        if (menu instanceof CallBack) {
            ((CallBack) menu).doFunc();
        } else {
            Intent intent = new Intent(getContext(), (Class<?>) menu);
            getContext().startActivity(intent);
        }
    }

    public static interface CallBack {
        void doFunc();
    }

    public void add(String menu, Class cls) {
        list.add(menu);
        data.put(data.size(), cls);
    }

    public void add(int menu, Class cls) {
        list.add(getContext().getResources().getString(menu));
        data.put(data.size(), cls);
    }

    public void add(String menu, CallBack call) {
        list.add(menu);
        data.put(data.size(), call);
    }

    public void add(int menu, CallBack call) {
        list.add(getContext().getResources().getString(menu));
        data.put(data.size(), call);
    }

    public void notifyDataSetChanged() {
        adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, list);
        setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
}
